/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名:UUMSController.java
 * <p>
 * 类产生时间: 2012-7-10 下午5:17:38
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 苏州公安统一用户管理平台
 * <p>
 * 所在部门: 电信/国土——技术二部
 * <p>
 * <p>
 */
package com.oceansoft.core.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hui.platform.system.Constants;
import com.hui.platform.system.utility.StringUtil;
import com.oceansoft.core.common.constant.Constant;
import com.oceansoft.core.common.constant.ConstantMap;
import com.oceansoft.core.common.util.Pagination;
import com.oceansoft.core.domain.Message;
import com.oceansoft.core.domain.RoleResource;
import com.oceansoft.core.domain.SysOperLog;
import com.oceansoft.core.domain.SysResource;
import com.oceansoft.core.domain.SysRole;
import com.oceansoft.core.domain.SysUser;
import com.oceansoft.core.domain.SysUserRole;
import com.oceansoft.core.service.ISysOperMgrService;
import com.oceansoft.core.service.ISysResourceService;
import com.oceansoft.core.service.IUUMSRoleService;

/**
 * 
 * @author chenw
 * 
 */
@Controller
@RequestMapping("/sys")
public class UUMSController {
	@Resource
	private IUUMSRoleService uumsRoleService;
	@Resource
	private ISysResourceService resourceService;
	@Resource
	private ISysOperMgrService operLogService;

	/**
	 * 进入角色列表界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/role/list.html")
	public String gotoRoleMgrIndex(SysRole condition, ModelMap model) {
		return "jump/jspz";
	}
	
	@RequestMapping("/role/list.json")
	public void list(ModelMap model, HttpServletRequest request) {
		int pageIndex = 1;
		String offset = request.getParameter("offset");
		String limit = request.getParameter("limit");
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		if(com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(offset)&&com.oceansoft.core.common.util.StringUtil.isNotNullAndBlank(limit)){
			pageIndex = Integer.parseInt(offset)/Integer.parseInt(limit)+1;
		}

		SysRole sysRole = new SysRole();
		String rname = request.getParameter("rname");
		sysRole.setRname(rname);
		Pagination<SysRole> page = uumsRoleService.findRolesByPage(sysRole,pageIndex);
		model.addAttribute("rows",page.getList());
		model.addAttribute("total",page.getTotalRows());
	}

	/**
	 * 进入角色列表界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/role/pluslist/{policeNum}")
	public String gotoRolePlusList(@PathVariable("policeNum") String policeNum,
			SysRole condition, ModelMap model) {
		//查询出所有的角色
		List<SysRole> list = uumsRoleService.findAllRoles();
		model.addAttribute("list", list);
		model.addAttribute("policeNum", policeNum);
		//根据警号查询出其具有的角色
		List<SysRole> checked = uumsRoleService.findRoles(policeNum);
		List listChecked = new ArrayList<Long>();
		for(SysRole fRole:checked){
			listChecked.add(fRole.getRcode());
		}
		model.addAttribute("checked", listChecked);
		return "system/role_plus";
	}
	/**
	 * 系统用户角色关联信息保存
	 * 
	 * @param roleId
	 * @param userRole
	 * @param model
	 * @param request
	 */                 
	@RequestMapping("/role/plusadd/{roleId}")
	public void plustRoleToUser(@PathVariable("roleId") String roleId,
			SysUserRole userRole, ModelMap model, HttpServletRequest request) {
		Message msg = new Message("角色新增人员成功！");
		try {
			
			if (StringUtils.hasText(userRole.getUserid())) {
				msg=uumsRoleService.plusAddRoleToUser(userRole.getUserid(),roleId);
			}
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("保存数据出错！");
			model.addAttribute("msg", msg);
		} finally {
			operLogService.saveLog(request, ConstantMap.MODUAL_SYS_MGR,
					msg.getBody());
		}
	}
	/**
	 * 角色新增或编辑界面初始化
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/role/init/{roleId}")
	public String gotoCreateSysRolePage(@PathVariable("roleId") String roleId,
			HttpServletRequest request, ModelMap model) {
		if (StringUtils.hasText(roleId) && "0".equals(roleId)) {
			model.addAttribute("data", new SysRole());
		} else {
			SysRole role = uumsRoleService.findRoleById(roleId);
			model.addAttribute("data", role);
		}
		return "system/role_add";
	}

	/**
	 * 系统角色新增
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/role/create")
	public void createSysRole(HttpServletRequest request, SysRole role,
			ModelMap model) {
		int operType = (StringUtils.hasText(role.getRcode()) && "0".equals(role
				.getRcode())) ? Constant.CREATE : Constant.UPDATE;
		String content = (StringUtils.hasText(role.getRcode()) && "0"
				.equals(role.getRcode())) ? "新增系统角色信息" : "编辑系统角色信息";
		Message msg = new Message("系统角色"
				+ ((StringUtils.hasText(role.getRcode()) && "0".equals(role
						.getRcode())) ? "创建" : "更新") + "成功！");
		try {
			int result = uumsRoleService.saveOrUpdateRole(role);
			model.addAttribute("msg", msg);
			if (result == 1) {
				msg.setBody("操作失败，名称不能重复");
				model.addAttribute("msg", msg);
				model.addAttribute("result", 1);
			} else {
				model.addAttribute("result", 0);
			}
		} catch (Exception e) {
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("系统角色数据保存时出错！");
			model.addAttribute("msg", msg);
			e.printStackTrace();
		} finally {
			// 记录操作日志
			model.addAttribute(Constant.LOG_RECORD,
					new SysOperLog(operType, msg.getBody(), content,
							ConstantMap.MODUAL_SYS_MGR, role.toString()));
		}
	}

	/**
	 * 初始化角色资源编辑页面
	 * 
	 * @param roleId
	 * @param model
	 * @return
	 */
	@RequestMapping("/role/resource/{roleId}")
	public String gotoSysRoleResourcePage(
			@PathVariable("roleId") String roleId, ModelMap model) {
		if (StringUtils.hasText(roleId)) {
			// 加载当前角色对应的资源信息
			List<SysResource> list1 = resourceService
					.findResourceByRoleId(roleId);
			// 加载所有资源信息
			List<SysResource> list2 = resourceService.findAllResources();
			model.addAttribute("roleresource", list1);
			model.addAttribute("allresource", list2);
		}
		return "system/role_resource";
	}

	/**
	 * 保存角色资源关联信息
	 * 
	 * @param request
	 * @param roleResource
	 * @param model
	 */
	@RequestMapping("/role/resource/create")
	public void saveRoleResourceData(HttpServletRequest request,
			RoleResource roleResource, ModelMap model) {
		Message msg = new Message("系统角色资源信息保存成功！");
		msg.setStatus(1);
		try {
			uumsRoleService.saveRoleResource(roleResource);
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("系统角色资源数据保存时出错！");
			msg.setStatus(0);
			model.addAttribute("msg", msg);
			e.printStackTrace();
		} finally {
			operLogService.saveLog(request, ConstantMap.MODUAL_SYS_MGR,
					msg.getBody());
		}
	}

	/**
	 * 查看系统角色关联的用户信息
	 * 
	 * @param roleId
	 */
	@RequestMapping("/role/users/{roleId}")
	public String viewRoleUsers(@PathVariable("roleId") String roleId,
			ModelMap model) {
		List<SysUser> users = uumsRoleService.findUsersByRoleId(roleId);
		model.addAttribute("roleId", roleId);
		model.addAttribute("users", users);
		return "system/role_users";
	}

	/**
	 * 系统用户角色关联信息保存
	 * 
	 * @param roleId
	 * @param userRole
	 * @param model
	 * @param request
	 */
	@RequestMapping("/role/relation/{roleId}")
	public void grantRoleToUser(@PathVariable("roleId") String roleId,
			SysUserRole userRole, ModelMap model, HttpServletRequest request) {
		Message msg = new Message("角色新增人员成功！");
		try {
			if (StringUtils.hasText(userRole.getUserid())) {
				String[] userIds = userRole.getUserid().split(",");
				Set<String> set = new HashSet<String>();
				set.addAll(Arrays.asList(userIds));
				msg = uumsRoleService.saveRoleUserData(roleId,
						set.toArray(new String[set.size()]));
			} else {
				msg = uumsRoleService.saveRoleUserData(roleId, new String[] {});
			}
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("保存数据出错！");
			model.addAttribute("msg", msg);
		} finally {
			operLogService.saveLog(request, ConstantMap.MODUAL_SYS_MGR,
					msg.getBody());
		}
	}

	/**
	 * 系统资源分页显示
	 * 
	 * @param pageIndex
	 * @param condition
	 * @param model
	 * @return
	 */
	@RequestMapping("/resource/list/{pageIndex}")
	public String gotoResourceMgrIndex(
			@PathVariable("pageIndex") int pageIndex, HttpServletRequest request,
			ModelMap model) {

		return "system/resource_list";
	}

	/**
	 * 资源新增界面初始化
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/resource/init")
	public String gotoCreateSysResourcePage(HttpServletRequest request,
			ModelMap model) {
		model.addAttribute("data", new SysResource());
		return "system/resource_add";
	}

	/**
	 * 资源新增界面初始化
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/resource/{resourceId}")
	public String gotoEditSysResourcePage(
			@PathVariable("resourceId") String resourceId,
			HttpServletRequest request, ModelMap model) {
		if (StringUtils.hasText(resourceId)) {
			SysResource resource = resourceService.findResourceById(resourceId);
			model.addAttribute("data", resource);
			// 记录操作日志
			// model.addAttribute(Constant.LOG_RECORD, new
			// SysOperLog(Constant.CREATE, "查看系统资源信息",
			// ConstantMap.MODUAL_SYS_MGR, resource.toString()));
		} else {
			model.addAttribute("data", new SysResource());
		}
		return "system/resource_add";
	}

	/**
	 * 删除系统资源信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/resource/{resourceId}", method = RequestMethod.DELETE)
	public void deleteSysResource(
			@PathVariable("resourceId") String resourceId,
			HttpServletRequest request, ModelMap model) {
		Message msg = new Message("系统资源删除成功！");
		try {
			if (StringUtils.hasText(resourceId)) {
				msg = resourceService.deleteSysResourceById(resourceId);
			}
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("删除系统资源失败！");
			e.printStackTrace();
		} finally {
			// 记录操作日志
			model.addAttribute(Constant.LOG_RECORD, new SysOperLog(
					Constant.DELETE, msg.getBody(), "删除系统资源信息",
					ConstantMap.MODUAL_SYS_MGR, "删除系统资源,资源编号:" + resourceId));
		}
	}

	/**
	 * 删除系统角色信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/role/{roleId}", method = RequestMethod.DELETE)
	public void deleteSysRole(@PathVariable("roleId") String roleId,
			HttpServletRequest request, ModelMap model) {
		Message msg = new Message("系统角色删除成功！");
		try {
			if (StringUtils.hasText(roleId)) {
				msg = uumsRoleService.deleteSysRoleRById(roleId);
			}
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("删除系统角色失败！");
			e.printStackTrace();
		} finally {
			// 记录操作日志
			model.addAttribute(Constant.LOG_RECORD, new SysOperLog(
					Constant.DELETE, msg.getBody(), "删除系统角色信息",
					ConstantMap.MODUAL_SYS_MGR, "删除系统角色，角色编号:" + roleId));
		}
	}

	/**
	 * 系统资源新增
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/resource/create")
	public void createSysResource(HttpServletRequest request,
			SysResource resource, ModelMap model) {
		int operType = StringUtils.hasText(resource.getResid()) ? Constant.UPDATE
				: Constant.CREATE;
		String content = StringUtils.hasText(resource.getResid()) ? "编辑系统资源信息"
				: "新增系统资源信息";
		String resid = request.getParameter("resid");
		Message msg = new Message("系统资源"
				+ (StringUtils.hasText(resource.getResid()) ? "更新" : "创建")
				+ "成功！");
		try {
			resourceService.saveOrUpdateResource(resource);
			model.addAttribute("msg", msg);
		} catch (Exception e) {
			msg.setStatus(Constant.RESULT_FAILD);
			msg.setBody("系统资源数据保存时出错！");
			model.addAttribute("msg", msg);
			e.printStackTrace();
		} finally {
			// 记录操作日志
			model.addAttribute(Constant.LOG_RECORD, new SysOperLog(operType,
					msg.getBody(), content, ConstantMap.MODUAL_SYS_MGR,
					resource.toString()));
		}
	}
	
	
	
	
	
	
	/**
	 * 系统资源分页显示
	 * 
	 * @param pageIndex
	 * @param condition
	 * @param model
	 * @return
	 */
	@RequestMapping("/resource/listggo.json")
	public ModelAndView gotoResourceMgrIndex1(HttpServletRequest request,
			ModelMap model) {
		ModelAndView modelAndView = new ModelAndView(Constants.RESPONSE_VIEW);
		String pageIndex1 = request.getParameter("page");
		if(StringUtil.isNull(pageIndex1))
		{
			pageIndex1 = "1";
		}
		
		String name = request.getParameter("name");
		
		
		int pageIndex = Integer.parseInt(pageIndex1);
		Pagination<SysResource> page = null;
		if (StringUtils.hasText(name)) {
			page = resourceService.findSysResourceByPage(name, pageIndex);
		} else {
			page = resourceService.findSysResourceByPage(pageIndex);
		}
		modelAndView.addObject("page",page);
		modelAndView.addObject("rows",page.getList());
		modelAndView.addObject("total",page.getTotalRows());
		return modelAndView;
	}
}
